from django.shortcuts import render,HttpResponseRedirect
from mqttClient import mqttclient
from .models import *
from django.contrib import messages
import time
import json
from django.shortcuts import redirect
from datetime import datetime
# Create your views here.
global login_msg,list,i
login_msg=0
i=0
list=[]
def on_message_login(client,userdata,msg):
    global i,login_msg
    i+=1
    if i % 2 == 1:
        login_msg=msg.payload.decode('utf-8')[5:15]
    elif i % 2 == 0:
        i=0


def on_message_register(client,userdata,msg):
    global list
    list.append(msg.payload.decode('utf-8')[5:15])
    print(list)
        

def index(request):
    return render(request,"index.html")


def login(request):
    global login_msg
    mqttclient.on_message=on_message_login
    mqttclient.publish('control','read')
    while login_msg == 0:
        time.sleep(1)
    p=IDCardInfo.objects.filter(card_id=login_msg).first()
    if p is not None:
        list=IDCardInfo.objects.filter(card_id=login_msg).all().values('status')
        uid=IDCardInfo.objects.filter(card_id=login_msg).all().values('card_id')
        print(list[0]['status'])
        if list[0]['status']==1:
            return HttpResponseRedirect('/home/?uid=%s' % uid[0]['card_id'])
        else:
            return HttpResponseRedirect('/super/')
    else:
        return render(request, "loginfailed.html")


def register(request):
    global list
    list=[]
    mqttclient.publish('control','read')
    mqttclient.on_message=on_message_register    
    while len(list)<2:
        time.sleep(1)
    p=IDCardInfo.objects.filter(card_id=list[0]).first()
    if p is not None:
        return render(request,"registerfailed.html")
    else:
        list=[]
        mqttclient.publish('control','write00')
        mqttclient.on_message=on_message_register
        mqttclient.publish('control','read')
        while len(list)<2:
            time.sleep(1)
        p=IDCardInfo(card_id=list[0],data=list[1])
        p.save()
        return render(request,"registersuccess.html")


def buy1(request):
    price=1
    shijian=datetime.now()
    uid=request.GET['uid']
    data=IDCardInfo.objects.filter(card_id=uid).all().values("data")
    money=data[0]['data']
    if money>=price: 
        global list
        list=[]
        mqttclient.on_message=on_message_register
        mqttclient.publish('control','read')
        while len(list)< 2:
            time.sleep(1)
        if list[0]==uid:
            money-=price
            IDCardInfo.objects.filter(card_id=uid).update(data=money)
            p=HistoryInfo(card_id=uid,goods_name="抽纸",time=shijian)
            p.save()
            mqttclient.publish('control','on')
            mqttclient.publish('control','write%03d' % money)         
            return render(request,"buysuccess.html",{'uid':uid})
        else:
            return render(request,"buyfailed.html",{'uid':uid})
    else:
        return render(request,"buyfailed.html",{'uid':uid})


def buy2(request):
    price=2
    shijian=datetime.now()
    uid=request.GET['uid']
    data=IDCardInfo.objects.filter(card_id=uid).all().values("data")
    money=data[0]['data']
    if money>=price:
        global list
        list=[]
        mqttclient.on_message=on_message_register
        mqttclient.publish('control','read')
        while len(list)< 2:
            time.sleep(1)
        if list[0]==uid:
            money-=price
            IDCardInfo.objects.filter(card_id=uid).update(data=money)
            p=HistoryInfo(card_id=uid,goods_name="卷纸",time=shijian)
            p.save()
            mqttclient.publish('control','on')
            mqttclient.publish('control','write%03d' % money)
            return render(request,"buysuccess.html",{'uid':uid})
        else:
            return render(request,"buyfailed.html",{'uid':uid})
    else:
        return render(request,'index.html')
        #return render(request,"buyfailed.html",{'uid':uid})


def charge(request,uid):
    user=IDCardInfo.objects.get(card_id=uid)
    if request.method=='GET':
        return render(request, 'charge.html', locals())
    else:  
        global list
        list=[]
        money=int(request.POST['money'])
        user.data+=money
        mqttclient.publish('control','write%03d' % user.data)
        mqttclient.on_message=on_message_register
        mqttclient.publish('control','read')
        while len(list)< 2:
            time.sleep(1)
        user.data=list[1]
        user.save()
        return HttpResponseRedirect('/super/') 
    

def home(request):
    id=request.GET['uid']
    return render(request,'home.html',{'uid':id})


def superadmin(request):
    users=IDCardInfo.objects.all()
    goods=GoodsInfo.objects.all()
    history=HistoryInfo.objects.all().order_by("-time")
    return render(request,'superadmin.html',locals())



def delete(request):
    uid=request.GET['uid']
    IDCardInfo.objects.filter(card_id=uid).delete()
    return HttpResponseRedirect('/super/')


def addamount(request):
    id=request.GET['id']
    GoodsInfo.objects.filter(id=id).update(amount=100)
    return HttpResponseRedirect('/super/')


def see(request):
    uid=request.GET['uid']
    p=IDCardInfo.objects.filter(card_id=uid).all().values('data')
    data=p[0]['data']
    return render(request,'see.html',{'uid':uid,'data':data})